import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
    Table, Button, Modal, Form, Input, Select, message, Spin, Space,
    Typography, Tag, Pagination, Tooltip, Checkbox, Row, Col, Drawer
} from 'antd';
import { PlusOutlined, SettingOutlined } from '@ant-design/icons';
import {
    getTeacherList,
    getTeacherById,
    addTeacher,
    editTeacher,
    deleteTeacher,
    Teacher,
    joinGroup,
    exitGroup,
    getGroupList,
    getTeacherGroupStudents,
    getTeacherEvaluations,
    addTeacherEvaluation,
    Evaluation as TeacherEvaluation,
    resetPassword
} from '@/utils/api/teacher/teacher';
import moment from 'moment';
import Search from "@/components/Teacher/search";
import { searchTeachers } from '@/utils/api/teacher/teacher';
import TeacherDetailModal from "@/components/Teacher/TeacherDetailModal";

const { Title } = Typography;
const { Option } = Select;

interface TeacherForAdd {
    id: number;
    name: string;
    sex: number;
    birthday: string;
    idCard: string;
    position: string;
}

interface TeacherForEdit extends TeacherForAdd {
    createTime: string;
}

interface Group {
    id: number;
    name: string;
    description?: string;
}

interface PaginationResponse {
    list: Teacher[];
    total: number;
    pages: number;
}

const TeacherList: React.FC = () => {
    const [teachers, setTeachers] = useState<Teacher[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [pages, setPages] = useState<number>(0);
    const [loading, setLoading] = useState<boolean>(false);
    const [currentTeacher, setCurrentTeacher] = useState<Teacher | null>(null);
    const [groups, setGroups] = useState<Group[]>([]);
    const [groupsLoading, setGroupsLoading] = useState<boolean>(false);

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    });

    const [visible, setVisible] = useState<boolean>(false);
    const [joinGroupVisible, setJoinGroupVisible] = useState<boolean>(false);
    const [exitGroupVisible, setExitGroupVisible] = useState<boolean>(false);
    const [currentId, setCurrentId] = useState<number | null>(null);
    const [selectedGroups, setSelectedGroups] = useState<number[]>([]);
    const [selectedExitGroups, setSelectedExitGroups] = useState<number[]>([]);
    const [joinedGroupIds, setJoinedGroupIds] = useState<number[]>([]);
    const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
    const [searchParams, setSearchParams] = useState<any>({});

    const [evaluationModalVisible, setEvaluationModalVisible] = useState<boolean>(false);
    const [evaluationStudents, setEvaluationStudents] = useState<Student[]>([]);
    const [evaluationLoading, setEvaluationLoading] = useState<boolean>(false);
    const [selectedEvaluationTeacher, setSelectedEvaluationTeacher] = useState<Teacher | null>(null);
    const [evaluationForm] = Form.useForm();

    const [form] = Form.useForm();

    const [resetPasswordVisible, setResetPasswordVisible] = useState<boolean>(false);
    const [resetPasswordLoading, setResetPasswordLoading] = useState<boolean>(false);
    const [resetPasswordTeacherId, setResetPasswordTeacherId] = useState<number | null>(null);
    const [resetPasswordTeacherName, setResetPasswordTeacherName] = useState<string>('');
    const [resetPasswordForm] = Form.useForm();

    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    const [currentTeacherRecord, setCurrentTeacherRecord] = useState<Teacher | null>(null);

    // 添加可选的页面大小选项
    const pageSizeOptions = useMemo(() => ['10', '20', '50', '100'], []);

    // 请求控制器ref，用于中断请求
    const abortControllerRef = useRef<AbortController | null>(null);

    // 防抖定时器ref
    const debounceRef = useRef<NodeJS.Timeout | null>(null);

    // 修改获取小组列表的函数
    const fetchGroups = useCallback(async () => {
        try {
            setGroupsLoading(true);
            const response = await getGroupList();

            if (response.data && Array.isArray(response.data.list)) {
                setGroups(response.data.list);
            } else {
                console.error('小组列表数据结构不符合预期:', response.data);
                setGroups([]);
            }
        } catch (error) {
            console.error('获取小组列表失败:', error);
            setGroups([]);
        } finally {
            setGroupsLoading(false);
        }
    }, []);

    const handleIdCardBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
        const idCard = e.target.value;
        const idCardPattern = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

        if (!idCardPattern.test(idCard) && idCard.length > 0) {
            message.error('请输入有效的18位身份证号');
        }
    }, []);

    const handlePhoneBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
        const phone = e.target.value;
        const phonePattern = /^1[3-9]\d{9}$/;

        if (!phonePattern.test(phone) && phone.length > 0) {
            message.error('请输入有效的11位手机号');
        }
    }, []);

    const fetchTeachers = useCallback(async (pageNum: number = 1, pageSize: number = 10, params: any = {}) => {
        // 中断之前的请求
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }

        // 创建新的AbortController
        const controller = new AbortController();
        abortControllerRef.current = controller;

        try {
            setLoading(true);

            // 判断是否有搜索参数，决定使用哪个API
            const hasSearchParams = Object.keys(params).length > 0;

            let response;
            if (hasSearchParams) {
                // 使用搜索API，参数放在请求体中
                const requestData = {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    ...params
                };
                response = await searchTeachers(requestData, { signal: controller.signal });
            } else {
                // 使用普通获取列表API，参数放在URL中
                const requestParams = {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    ...params
                };
                response = await getTeacherList(requestParams, { signal: controller.signal });
            }

            // 检查请求是否被中止
            if (controller.signal.aborted) {
                return;
            }

            const data = response.data as PaginationResponse;
            const list = data.list.map((teacher: Teacher) => ({
                ...teacher,
                createTime: teacher.createTime ?
                    moment(teacher.createTime).format('YYYY-MM-DD HH:mm:ss') :
                    moment().format('YYYY-MM-DD HH:mm:ss')
            }));

            setTeachers(list);
            setTotal(data.total);
            setPages(data.pages);

            setPagination(prev => ({
                ...prev,
                current: pageNum,
                pageSize
            }));
        } catch (error: any) {
            // 如果是中止请求的错误，不显示错误信息
            if (error.name === 'AbortError') {
                console.log('请求被中止');
                return;
            }
            console.error('获取老师列表失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        fetchTeachers(pagination.current, pagination.pageSize);

        // 清理函数：组件卸载时中止所有请求
        return () => {
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
        };
    }, [fetchTeachers]);

    // 修改分页处理函数
    const handleTableChange = useCallback((page: number, pageSize?: number) => {
        // 清除之前的防抖定时器
        if (debounceRef.current) {
            clearTimeout(debounceRef.current);
        }

        // 设置新的防抖定时器
        debounceRef.current = setTimeout(() => {
            const newPageSize = pageSize || pagination.pageSize;
            setPagination({
                current: page,
                pageSize: newPageSize,
            });
            fetchTeachers(page, newPageSize, searchParams);
        }, 100); // 100ms防抖延迟
    }, [fetchTeachers, pagination.pageSize, searchParams]);

    // 添加搜索处理函数
    const handleSearch = useCallback((params: any) => {
        // 转换参数格式
        const searchData = {
            ...params,
            sex: params.sex !== undefined ? Number(params.sex) : undefined,
            age: params.age ? Number(params.age) : undefined
        };

        // 移除空值
        Object.keys(searchData).forEach(key => {
            if (searchData[key] === undefined || searchData[key] === '') {
                delete searchData[key];
            }
        });

        setSearchParams(searchData);
        fetchTeachers(1, pagination.pageSize, searchData);
    }, [fetchTeachers, pagination.pageSize]);

    // 添加重置处理函数
    const handleReset = useCallback(() => {
        setSearchParams({});
        fetchTeachers(1, pagination.pageSize);
    }, [fetchTeachers, pagination.pageSize]);

    const handleDetail = useCallback(async (id: number) => {
        try {
            setLoading(true);
            setCurrentId(id);
            const response = await getTeacherById(id);
            const teacher = response.data;

            setCurrentTeacher(teacher);
            setDetailModalVisible(true);
        } catch (error) {
            console.error('获取教师详情失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    const handleAdd = useCallback(() => {
        setCurrentId(null);
        setCurrentTeacher(null);
        form.resetFields();
        setVisible(true);
    }, [form]);

    const handleEdit = useCallback(async (id: number) => {
        try {
            setLoading(true);
            setCurrentId(id);
            const response = await getTeacherById(id);
            const teacher = response.data;

            setCurrentTeacher(teacher);

            form.setFieldsValue({
                name: teacher.name,
                sex: teacher.sex,
                idCard: teacher.idCard,
                position: teacher.position,
                phone: teacher.phone,
            });
            setVisible(true);
        } catch (error) {
            console.error('获取老师详情失败:', error);
        } finally {
            setLoading(false);
        }
    }, [form]);

    const handleSubmit = useCallback(async () => {
        try {
            const values = await form.validateFields();
            setLoading(true);

            if (currentId) {
                const editData = {
                    id: currentId,
                    name: values.name,
                    idCard: values.idCard,
                    phone: values.phone,
                    position: values.position,
                    createTime: currentTeacher?.createTime ?
                        moment(currentTeacher.createTime).format('YYYY-MM-DD HH:mm:ss') :
                        moment().format('YYYY-MM-DD HH:mm:ss'),
                    groupId: currentTeacher?.groupId
                };

                try {
                    await editTeacher(editData);
                    message.success("编辑成功");
                } catch (error) {
                    console.error('编辑请求失败:', error);
                    throw error;
                }
            } else {
                const addData = {
                    name: values.name,
                    idCard: values.idCard,
                    phone: values.phone,
                    position: values.position,
                };
                try {
                    await addTeacher(addData);
                    message.success("添加成功");
                } catch (error) {
                    console.error('新增请求失败:', error);
                    throw error;
                }
            }

            fetchTeachers(pagination.current, pagination.pageSize, searchParams);
            setVisible(false);
            setCurrentId(null);
        } catch (error) {
            console.error('操作失败:', error);

        } finally {
            setLoading(false);
        }
    }, [form, currentId, currentTeacher, fetchTeachers, pagination.current, pagination.pageSize, searchParams]);

    // 添加处理评价按钮点击的函数
    const handleEvaluate = useCallback(async (teacher: Teacher) => {
        if (!teacher.groupId) {
            message.warning('该老师未指导任何小组，无法评价');
            return;
        }

        try {
            setEvaluationLoading(true);
            setSelectedEvaluationTeacher(teacher);

            // 获取该老师所在小组的学生
            const response = await getTeacherGroupStudents(teacher.groupId);
            if (response.code === 200) {
                const students = response.data || [];
                setEvaluationStudents(Array.isArray(students) ? students : []);
                setEvaluationModalVisible(true);
            }
        } catch (error) {
            console.error('获取学生列表失败:', error);
        } finally {
            setEvaluationLoading(false);
        }
    }, []);

    // 添加提交评价的函数
    const handleEvaluationSubmit = useCallback(async () => {
        try {
            const values = await evaluationForm.validateFields();

            Modal.confirm({
                title: '确认提交评价',
                content: '您确定要提交此评价吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    try {
                        setEvaluationLoading(true);

                        // 获取选中的学生信息
                        const selectedStudent = evaluationStudents.find(student => student.id === values.studentId);

                        const evaluationData: TeacherEvaluation = {
                            teacherId: selectedEvaluationTeacher?.id as number,
                            teacherName: selectedEvaluationTeacher?.name,
                            studentId: values.studentId,
                            studentName: selectedStudent?.name,
                            evaluation: values.evaluation
                        };

                        const response = await addTeacherEvaluation(evaluationData);
                        if (response.code === 200) {
                            message.success('评价成功');
                            setEvaluationModalVisible(false);
                            evaluationForm.resetFields();
                            setEvaluationStudents([]); // 清空学生列表
                            setSelectedEvaluationTeacher(null);
                        }
                    } catch (error) {
                        console.error('评价失败:', error);
                    } finally {
                        setEvaluationLoading(false);
                    }
                }
            });
        } catch (error) {
            console.error('表单验证失败:', error);
        }
    }, [selectedEvaluationTeacher, evaluationForm, evaluationStudents]);

    const handleDelete = useCallback(async (id: number) => {
        Modal.confirm({
            title: "确认删除",
            content: "确定要删除这位老师吗？此操作不可恢复",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
                try {
                    setLoading(true);
                    await deleteTeacher(id);
                    message.success("删除成功");

                    const currentPage = pagination.current;
                    const isLastItemOnPage = teachers.length === 1;

                    if (isLastItemOnPage && currentPage > 1) {
                        fetchTeachers(currentPage - 1, pagination.pageSize);
                    } else {
                        fetchTeachers(currentPage, pagination.pageSize);
                    }
                } catch (error) {
                    console.error("删除失败:", error);
                } finally {
                    setLoading(false);
                }
            }
        });
    }, [pagination.current, pagination.pageSize, teachers.length, fetchTeachers]);

    // 打开加入小组模态框时获取小组列表
    const handleJoinGroup = useCallback(async (record: Teacher) => {
        setCurrentId(record.id);

        // 解析当前老师已加入的小组ID
        const joinedGroupIds = record.groupId ?
            record.groupId.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id)) : [];

        setJoinedGroupIds(joinedGroupIds);
        setSelectedGroups(joinedGroupIds);
        setJoinGroupVisible(true);

        // 只有在点击加入小组时才获取小组列表
        await fetchGroups();
    }, [fetchGroups]);

    const handleJoinGroupSubmit = useCallback(async () => {
        if (!currentId) return;

        const newSelectedGroups = selectedGroups.filter(id => !joinedGroupIds.includes(id));

        if (newSelectedGroups.length === 0) {
            message.warning('请至少选择一个新加入的小组');
            return;
        }

        Modal.confirm({
            title: '确认加入小组',
            content: `您确定要加入选中的 ${newSelectedGroups.length} 个小组吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    setLoading(true);
                    const groupIds = newSelectedGroups.join(',');
                    await joinGroup(currentId, groupIds);
                    message.success('加入小组成功');
                    setJoinGroupVisible(false);
                    fetchTeachers(pagination.current, pagination.pageSize, searchParams);
                } catch (error) {
                    console.error('加入小组失败:', error);
                } finally {
                    setLoading(false);
                }
            }
        });
    }, [currentId, selectedGroups, joinedGroupIds, fetchTeachers, pagination.current, pagination.pageSize, searchParams]);

    const handleExitGroup = useCallback(async (id: number, groupIds: string) => {
        setCurrentId(id);
        const joinedGroupIds = groupIds ? groupIds.split(',').map(id => parseInt(id.trim())) : [];
        setJoinedGroupIds(joinedGroupIds);
        setSelectedExitGroups([]);
        setExitGroupVisible(true);

        // 如果小组列表为空，则获取小组列表
        if (groups.length === 0) {
            await fetchGroups();
        }
    }, [groups.length, fetchGroups]);

    const handleExitGroupSubmit = useCallback(async () => {
        if (!currentId) return;

        if (selectedExitGroups.length === 0) {
            message.warning('请至少选择一个要退出的小组');
            return;
        }

        Modal.confirm({
            title: '确认退出小组',
            content: `您确定要退出选中的 ${selectedExitGroups.length} 个小组吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    setLoading(true);
                    const groupIds = selectedExitGroups.join(',');
                    await exitGroup(currentId, groupIds);
                    message.success('退出小组成功');
                    setExitGroupVisible(false);
                    fetchTeachers(pagination.current, pagination.pageSize, searchParams);
                } catch (error) {
                    console.error('退出小组失败:', error);
                } finally {
                    setLoading(false);
                }
            }
        });
    }, [currentId, selectedExitGroups, fetchTeachers, pagination.current, pagination.pageSize, searchParams]);

    // 添加重置密码处理函数
    const handleResetPassword = useCallback(async (teacherId: number, teacherName: string) => {
        setResetPasswordTeacherId(teacherId);
        setResetPasswordTeacherName(teacherName);
        setResetPasswordVisible(true);
    }, []);

// 添加重置密码提交函数
    const handleResetPasswordSubmit = useCallback(async () => {
        try {
            const values = await resetPasswordForm.validateFields();
            setResetPasswordLoading(true);

            const response = await resetPassword(resetPasswordTeacherId as number, values.password);

            if (response.code === 200) {
                message.success('密码重置成功');
                resetPasswordForm.resetFields();
                setResetPasswordVisible(false);
            }
        } catch (error) {
            console.error('密码重置失败:', error);
        } finally {
            setResetPasswordLoading(false);
        }
    }, [resetPasswordTeacherId, resetPasswordForm]);

    // 显示抽屉
    const showDrawer = useCallback((record: Teacher) => {
        setCurrentTeacherRecord(record);
        setDrawerVisible(true);
    }, []);

    // 关闭抽屉
    const closeDrawer = useCallback(() => {
        setDrawerVisible(false);
        setCurrentTeacherRecord(null);
    }, []);

    // 操作按钮点击处理函数
    const handleDrawerAction = useCallback((action: string, record: Teacher) => {
        closeDrawer();

        switch (action) {
            case 'detail':
                handleDetail(record.id);
                break;
            case 'edit':
                handleEdit(record.id);
                break;
            case 'evaluate':
                handleEvaluate(record);
                break;
            case 'joinGroup':
                handleJoinGroup(record);
                break;
            case 'exitGroup':
                handleExitGroup(record.id, record.groupId || '');
                break;
            case 'resetPassword':
                handleResetPassword(record.id, record.name);
                break;
            case 'delete':
                handleDelete(record.id);
                break;
            default:
                break;
        }
    }, [closeDrawer, handleDetail, handleEdit, handleEvaluate, handleJoinGroup, handleExitGroup, handleResetPassword, handleDelete]);


    const columns = useMemo(() => [
        {
            title: '序号',
            key: 'index',
            className: 'table-cell',
            align:'center',

            render: (text: any, record: Teacher, index: number) => {
                const serialNumber = (pagination.current - 1) * pagination.pageSize + index + 1;
                return serialNumber;
            }
        },
        {
            title: '姓名（年龄）',
            key: 'nameAge',
            className: 'table-cell',
            align:'center',

            render: (record: Teacher) => (
                <span>
                    {record.name}（{record.age}）
                </span>
            ),
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            className: 'table-cell',
            align:'center',

            render: (sex: number) => (
                <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <Tag color={sex === 0 ? 'pink' : 'blue'}>
                        {sex === 0 ? '女' : '男'}
                    </Tag>
                </div>
            ),
        },
        {
            title: '职务',
            dataIndex: 'position',
            key: 'position',
            className: 'table-cell',
            align:'center',
            render: (position: string) => position || '-',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            className: 'table-cell',
            align:'center',

            render: (phone: string) => phone || '-',
        },
        {
            title: '所在小组',
            key: 'groupName',
            className: 'table-cell',
            align:'center',

            render: (record: Teacher) => (
                record.groupName && record.groupName.length > 0 ? (
                    <Tooltip title={record.groupName.join(', ')}>
                        <span>
                            {record.groupName.join(', ').length > 18
                                ? record.groupName.join(', ').substring(0, 18) + '...'
                                : record.groupName.join(', ')}
                        </span>
                    </Tooltip>
                ) : '无'
            ),
        },
        {
            title: '操作',
            key: 'action',
            className: 'table-cell',
            align:'center',
            render: (_: any, record: Teacher) => (
                <Button
                    className="operation-menu-btn"
                    size="small"
                    onClick={() => showDrawer(record)}
                >
                    <SettingOutlined style={{ marginRight: 2 }} />
                    操作菜单
                </Button>
            ),
        },
    ], [pagination.current, pagination.pageSize, showDrawer]);

    return (
        <div className="teacher-list-container" style={{ padding: '10px' }}>
            <Search onSearch={handleSearch} onReset={handleReset}/>
            <TeacherDetailModal
                visible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
                teacherId={currentId}
                currentTeacher={currentTeacher}
            />
            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '20px',
                paddingBottom: '10px',
                borderBottom: '1px solid #f0f0f0'
            }}>
                <Title level={4} style={{ margin: 0 }}>老师列表</Title>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAdd}
                    className="add-teacher-btn"
                >
                    新增老师
                </Button>
            </div>

            <Spin spinning={loading}>
                <div style={{
                    overflowX: 'auto',
                    borderRadius: '6px',
                    marginBottom: '26px'
                }}>
                    <Table<Teacher>
                        columns={columns}
                        dataSource={teachers}
                        rowKey="id"
                        pagination={false}
                        style={{ minWidth: '100%' }}
                        scroll={{ y: 500, x: 'max-content' }}
                    />
                </div>

                <div style={{
                    display: 'flex',
                    justifyContent: 'flex-end',
                    alignItems: 'center'
                }}>
                    <Pagination
                        current={pagination.current}
                        pageSize={pagination.pageSize}
                        total={total}
                        showSizeChanger
                        pageSizeOptions={pageSizeOptions}
                        showQuickJumper
                        showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`}
                        onChange={handleTableChange}
                        onShowSizeChange={handleTableChange}
                    />
                </div>
            </Spin>

            {/* 操作抽屉 */}
            <Drawer
                title={`操作菜单 - ${currentTeacherRecord?.name || ''}`}
                placement="right"
                onClose={closeDrawer}
                open={drawerVisible}
                width={400}
            >
                {currentTeacherRecord && (
                    <Space direction="vertical" style={{ width: '100%' }} size="middle">
                        <Button
                            block
                            className="detail-btn"
                            onClick={() => handleDrawerAction('detail', currentTeacherRecord)}
                        >
                            详情
                        </Button>
                        <Button
                            block
                            className="edit-btn"
                            onClick={() => handleDrawerAction('edit', currentTeacherRecord)}
                        >
                            编辑
                        </Button>
                        <Button
                            block
                            className="evaluate-btn"
                            onClick={() => handleDrawerAction('evaluate', currentTeacherRecord)}
                        >
                            评价
                        </Button>
                        <Button
                            block
                            className="join-group-btn"
                            onClick={() => handleDrawerAction('joinGroup', currentTeacherRecord)}
                        >
                            加入小组
                        </Button>
                        <Button
                            block
                            className="exit-group-btn"
                            disabled={!currentTeacherRecord.groupId || currentTeacherRecord.groupId.trim() === ''}
                            onClick={() => handleDrawerAction('exitGroup', currentTeacherRecord)}
                        >
                            退出小组
                        </Button>
                        <Button
                            block
                            className="reset-password-btn"
                            onClick={() => handleDrawerAction('resetPassword', currentTeacherRecord)}
                        >
                            重置密码
                        </Button>
                        <Button
                            block
                            className="delete-btn"
                            onClick={() => handleDrawerAction('delete', currentTeacherRecord)}
                        >
                            删除
                        </Button>
                    </Space>
                )}
            </Drawer>

            <Modal
                title={currentId ? "编辑老师" : "新增老师"}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={[
                    <Button key="cancel" onClick={() => setVisible(false)}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
                        确定
                    </Button>,
                ]}
                destroyOnClose={true}
                width={600}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="name"
                        label="姓名"
                        rules={[{ required: true, message: '请输入姓名' }]}
                    >
                        <Input placeholder="请输入姓名" />
                    </Form.Item>

                    <Form.Item
                        name="idCard"
                        label="身份证号"
                        rules={[
                            { required: true, message: '请输入身份证号' },
                            {
                                pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                                message: '请输入有效的18位身份证号'
                            }
                        ]}
                    >
                        <Input
                            placeholder="请输入身份证号"
                            maxLength={18}
                            onBlur={handleIdCardBlur}
                        />
                    </Form.Item>

                    <Form.Item
                        name="position"
                        label="职务"
                        rules={[{ required: true, message: '请输入职务' }]}
                    >
                        <Input placeholder="请输入职务，如：班主任、语文老师等" />
                    </Form.Item>

                    <Form.Item
                        name="phone"
                        label="手机号"
                        rules={[
                            { required: true, message: '请输入手机号' },
                            {
                                pattern: /^1[3-9]\d{9}$/,
                                message: '请输入有效的11位手机号'
                            }
                        ]}
                    >
                        <Input
                            placeholder="请输入手机号"
                            maxLength={11}
                            onBlur={handlePhoneBlur}
                        />
                    </Form.Item>

                    <Form.Item label="创建时间">
                        <Input
                            disabled
                            value={currentId && currentTeacher ?
                                moment(currentTeacher.createTime).format('YYYY-MM-DD HH:mm:ss') :
                                "系统自动生成"
                            }
                        />
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                title="评价老师"
                open={evaluationModalVisible}
                onCancel={() => {
                    setEvaluationModalVisible(false);
                    evaluationForm.resetFields();
                    setEvaluationStudents([]); // 清空学生列表
                    setSelectedEvaluationTeacher(null);
                }}
                footer={[
                    <Button key="cancel" onClick={() => setEvaluationModalVisible(false)}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        loading={evaluationLoading}
                        onClick={handleEvaluationSubmit}
                    >
                        提交评价
                    </Button>,
                ]}
                width={600}
            >
                <Spin spinning={evaluationLoading}>
                    <Form
                        form={evaluationForm}
                        layout="vertical"
                    >
                        <Form.Item
                            name="studentId"
                            label="选择学生"
                            rules={[{ required: true, message: '请选择学生' }]}
                        >
                            <Select placeholder="请选择学生">
                                {evaluationStudents.map(student => (
                                    <Option key={student.id} value={student.id}>
                                        {student.name}（{student.studentNumber}）
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                        <Form.Item
                            name="evaluation"
                            label="评价内容"
                            rules={[{ required: true, message: '请输入评价内容' }]}
                        >
                            <Input.TextArea
                                rows={4}
                                placeholder="请输入对老师的评价"
                                maxLength={500}
                                showCount
                            />
                        </Form.Item>
                    </Form>
                </Spin>
            </Modal>

            <Modal
                title="加入小组"
                open={joinGroupVisible}
                onCancel={() => setJoinGroupVisible(false)}
                footer={[
                    <Button key="cancel" onClick={() => setJoinGroupVisible(false)}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleJoinGroupSubmit}>
                        确定
                    </Button>,
                ]}
                width={700}
            >
                <Spin spinning={groupsLoading}>
                    {groups && groups.length > 0 ? (
                        <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
                            <Checkbox.Group
                                value={selectedGroups}
                                onChange={(values) => {
                                    const joinedIds = joinedGroupIds || [];
                                    const newValues = [...joinedIds, ...values.filter(v => !joinedIds.includes(v))];
                                    setSelectedGroups(newValues);
                                }}
                                style={{ width: '100%' }}
                            >
                                <Row gutter={[16, 16]}>
                                    {groups.map(group => {
                                        const isJoined = joinedGroupIds.includes(group.id);
                                        return (
                                            <Col span={8} key={group.id}>
                                                <Checkbox
                                                    value={group.id}
                                                    disabled={isJoined}
                                                    checked={isJoined}
                                                >
                                                    {group.name}
                                                    {isJoined && <span style={{ color: '#999', marginLeft: '4px' }}>(已加入)</span>}
                                                </Checkbox>
                                            </Col>
                                        );
                                    })}
                                </Row>
                            </Checkbox.Group>
                        </div>
                    ) : (
                        <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                            {groupsLoading ? '加载中...' : '暂无小组'}
                        </div>
                    )}
                </Spin>
            </Modal>

            <Modal
                title="退出小组"
                open={exitGroupVisible}
                onCancel={() => setExitGroupVisible(false)}
                footer={[
                    <Button key="cancel" onClick={() => setExitGroupVisible(false)}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleExitGroupSubmit}>
                        确定
                    </Button>,
                ]}
                width={700}
            >
                {joinedGroupIds.length > 0 ? (
                    <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
                        <Checkbox.Group
                            value={selectedExitGroups}
                            onChange={setSelectedExitGroups}
                            style={{ width: '100%' }}
                        >
                            <Row gutter={[16, 16]}>
                                {groups
                                    .filter(group => joinedGroupIds.includes(group.id))
                                    .map(group => (
                                        <Col span={8} key={group.id}>
                                            <Checkbox value={group.id}>{group.name}</Checkbox>
                                        </Col>
                                    ))
                                }
                            </Row>
                        </Checkbox.Group>
                    </div>
                ) : (
                    <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                        该老师未加入任何小组
                    </div>
                )}
            </Modal>

            <Modal
                title={`重置密码 - ${resetPasswordTeacherName}`}
                open={resetPasswordVisible}
                onCancel={() => {
                    setResetPasswordVisible(false);
                    resetPasswordForm.resetFields();
                }}
                footer={[
                    <Button key="cancel" onClick={() => setResetPasswordVisible(false)}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        loading={resetPasswordLoading}
                        onClick={handleResetPasswordSubmit}
                    >
                        确定
                    </Button>,
                ]}
                width={400}
            >
                <Form
                    form={resetPasswordForm}
                    layout="vertical"
                >
                    <Form.Item
                        name="password"
                        label="新密码"
                        rules={[
                            { required: true, message: '请输入新密码' },
                            { min: 6, message: '密码长度不能少于6位' }
                        ]}
                    >
                        <Input.Password placeholder="请输入新密码" />
                    </Form.Item>

                    <Form.Item
                        name="confirmPassword"
                        label="确认密码"
                        dependencies={['password']}
                        rules={[
                            { required: true, message: '请确认密码' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}
                    >
                        <Input.Password placeholder="请再次输入密码" />
                    </Form.Item>
                </Form>
            </Modal>

            <style>{`
                .table-cell {
                    padding: 4px 4px;
                    white-space: nowrap;
                    text-align: center;
                }
                .ant-table-thead > tr > th {
                    position: sticky;
                    top: 0;
                    z-index: 1;
                    background-color: #fafafa;
                    font-weight: 600;
                    text-align: center;
                    padding: 8px 4px;
                }
    
                .ant-table-container {
                    position: relative;
                }
    
                .ant-table-tbody > tr:hover > td {
                    background-color: #f5f5f5;
                }
                
                .add-teacher-btn {
                    background: linear-gradient(135deg, #1677ff 0%, #40a9ff 100%) !important;
                    border: none !important;
                }
    
                /* 抽屉按钮样式 */
                .ant-drawer-body .ant-btn {
                    background: transparent !important;
                    border: none !important;
                    box-shadow: none !important;
                    text-align: left;
                    padding: 12px 16px;
                    height: auto;
                    border-radius: 6px;
                    transition: all 0.2s ease;
                    color: rgba(0, 0, 0, 0.85);
                    font-size: 14px;
                    display: flex;
                    align-items: center;
                    margin-bottom: 4px;
                    width: 100%;
                    position: relative;
                    overflow: hidden;
                }
    
                /* 按钮悬停效果 */
                .ant-drawer-body .ant-btn:hover {
                    background: rgba(24, 144, 255, 0.1) !important;
                    color: #1890ff !important;
                    transform: translateX(4px);
                }
    
                /* 按钮激活效果 */
                .ant-drawer-body .ant-btn:active {
                    background: rgba(24, 144, 255, 0.2) !important;
                    transform: translateX(4px) scale(0.98);
                }
    
                /* 禁用状态按钮 */
                .ant-drawer-body .ant-btn[disabled] {
                    color: rgba(0, 0, 0, 0.25) !important;
                    background: transparent !important;
                    cursor: not-allowed;
                }
    
                .ant-drawer-body .ant-btn[disabled]:hover {
                    transform: none;
                    color: rgba(0, 0, 0, 0.25) !important;
                    background: transparent !important;
                }
    
                /* 添加按钮图标样式 */
                .ant-drawer-body .ant-btn > .anticon {
                    margin-right: 8px;
                    font-size: 16px;
                    transition: transform 0.2s ease;
                }
    
                .ant-drawer-body .ant-btn:hover > .anticon {
                    transform: scale(1.1);
                }
                
                /* 编辑按钮特殊样式 */
                .ant-drawer-body .edit-btn:hover {
                    background: rgba(82, 196, 26, 0.1) !important;
                    color: #52c41a !important;
                }
                
                .ant-drawer-body .edit-btn:active {
                    background: rgba(82, 196, 26, 0.2) !important;
                }
    
                /* 删除按钮特殊样式 */
                .ant-drawer-body .delete-btn:hover {
                    background: rgba(255, 77, 79, 0.1) !important;
                    color: #ff4d4f !important;
                }
    
                .ant-drawer-body .delete-btn:active {
                    background: rgba(255, 77, 79, 0.2) !important;
                }
    
                /* 评价按钮特殊样式 */
                .ant-drawer-body .evaluate-btn:hover {
                    background: rgba(114, 46, 209, 0.1) !important;
                    color: #722ed1 !important;
                }
    
                .ant-drawer-body .evaluate-btn:active {
                    background: rgba(114, 46, 209, 0.2) !important;
                }
    
                /* 重置密码按钮特殊样式 */
                .ant-drawer-body .reset-password-btn:hover {
                    background: rgba(82, 196, 26, 0.1) !important;
                    color: #52c41a !important;
                }
    
                .ant-drawer-body .reset-password-btn:active {
                    background: rgba(82, 196, 26, 0.2) !important;
                }
                
                /* 加入小组按钮特殊样式 */
                .ant-drawer-body .join-group-btn:hover {
                    background: rgba(255, 199, 0, 0.1) !important;
                    color: #ffc700 !important;
                }
                
                .ant-drawer-body .join-group-btn:active {
                    background: rgba(255, 199, 0, 0.2) !important;
                }
                
                /* 操作按钮样式 */
                .operation-menu-btn {
                    padding: 2px 7px !important;
                    height: 30px !important;
                    
                    background: linear-gradient(135deg, #00c3f4 0%, #4cd1af 100%) !important;
                    border: none !important;
                    color: #ffffff !important;
                    border-radius: 8px;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    box-shadow: 
                        0 2px 4px rgba(0, 0, 0, 0.2),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1);
    
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    font-weight: 500;
                    font-size: 13px;
                    letter-spacing: 0.3px;
                }

                .operation-menu-btn:hover {
                    background: linear-gradient(135deg, #34495e 0%, #56789a 100%) !important;
                    color: #ffffff !important;
                    transform: translateY(-2px);
                    box-shadow: 
                        0 4px 10px rgba(0, 0, 0, 0.25),
                        inset 0 1px 0 rgba(255, 255, 255, 0.15);
                }

                .operation-menu-btn:active {
                    background: linear-gradient(135deg, #243342 0%, #3a5674 100%) !important;
                    transform: translateY(0);
                    box-shadow: 
                        0 2px 4px rgba(0, 0, 0, 0.2),
                        inset 0 1px 0 rgba(255, 255, 255, 0.05);
                }

                .operation-menu-btn .anticon {
                    font-size: 14px;
                    transition: transform 0.2s ease;
                }

                .operation-menu-btn:hover .anticon {
                    transform: rotate(30deg);
                }

    
                .ant-btn-primary {
                    transition: all 0.3s ease;
                }
    
                .ant-btn-primary:hover {
                    transform: translateY(-2px);
                }
    
                .ant-btn-primary:active {
                    transform: translateY(0);
                }
            `}</style>
        </div>
    );
};

export default React.memo(TeacherList);